﻿Imports MapleLib.PacketLib
Imports System.Data.SqlClient
Imports System.Web

Public Class LoginHandler
#Region "IDisposable"
    Implements IDisposable

    Public Sub Dispose() Implements IDisposable.Dispose

    End Sub
#End Region

    Public Sub New(ByVal c As MapleClient, ByVal m As Main, ByVal Reader As PacketReader)
        Dim UserName As String = Reader.ReadMapleString()
        Dim Password As String = Reader.ReadMapleString()
        c.LoggedIn = CheckLogin(UserName, Password, c)
        If c.LoggedIn Then
            c.AccountName = UserName
            Dim toSend As New PacketWriter
            toSend.WriteShort(SendHeaders.UnkownBA)
            toSend.WriteByte(0)
            c.SendPacket(toSend)

            For Each Item In Settings.WorldSettings
                c.SendPacket(MaplePacketCreator.GetServerList(Item))
            Next

            toSend = New PacketWriter
            toSend.WriteShort(SendHeaders.ServerList)
            toSend.WriteByte(&HFF)
            c.SendPacket(toSend)

            toSend.WriteShort(SendHeaders.ServerListEnd)
            toSend.WriteInt(0)
            c.SendPacket(toSend)

            toSend.WriteShort(SendHeaders.ServerListInfo)
            toSend.WriteByte(0)
            c.SendPacket(toSend)
        Else
            'TODO, invalid login handling
        End If
    End Sub

    Public Function CheckLogin(ByVal UserName As String, ByVal Password As String, ByVal c As MapleClient) As Boolean
        Dim sql As New MSSQL
        UserName = HttpUtility.HtmlEncode(UserName)
        Password = HttpUtility.HtmlEncode(Password)
        Dim query As String = String.Format("SELECT * FROM tbl_account WHERE name='{0}' AND pass='{1}'", UserName, Password)
        Dim i As Integer = 0
        Using reader As SqlDataReader = sql.OpenRS(query)
            While reader.Read()
                i = reader("id")
                c.AccountID = i
            End While
        End Using
        sql.Close()
        Return i > 0
    End Function
End Class
